package com.hlz.rabbit.mq.dead;

import com.hlz.rabbit.mq.util.RabbitMqUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 死信队列生产者
 *
 * @author Hongliang Zhu
 * @create 2022-11-21 22:15
 */
public class DeadProducer {

    public static void main(String[] args) throws IOException, TimeoutException {
        try (Channel channel = RabbitMqUtils.getChannel()) {
            channel.exchangeDeclare("normal_exchange", BuiltinExchangeType.DIRECT);

            // 死信交换机
            channel.exchangeDeclare("dead-exchange", BuiltinExchangeType.DIRECT);

            // 声明死信队列
            channel.queueDeclare("dead-queue", false, false, false, null);
            // 死信队列绑定死信交换机
            channel.queueBind("dead-queue", "dead-exchange", "lisi");

            // 正常队列绑定死信队列信息
            Map<String, Object> params = new HashMap<>();
            // 正常队列设置死信交换机
            params.put("x-dead-letter-exchange", "dead-exchange");
            //正常队列设置死信 routing-key
            params.put("x-dead-letter-routing-key", "lisi");

            // 设置队列长度限制
            params.put("x-max-length", 6);

            // 声明正常队列
            String normalQueue = "normal-queue";
            channel.queueDeclare(normalQueue, false, false, false, params);
            channel.queueBind(normalQueue, "normal_exchange", "zhangsan");

            // 设置消息的ttl时间
//            AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder().expiration("10000").build();


            for (int i = 1; i <= 10; i++) {
                String message = "info" + i;
                channel.basicPublish("normal_exchange", "zhangsan", null, message.getBytes());
                System.out.println("生产者发送消息:" + message);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
